<template>
<!-- category 1 -->
	<mescroll-uni @init="mescrollInit" :up="upOption" :down="downOption" @down="downCallback" @up="upCallback">
		<view class="content">
			<view :style='{"minHeight":"100%","width":"100%","padding":"0 30rpx","position":"relative","background":"#F3F3F3","height":"auto"}'>
				<!-- <view class="page-title" :style='{"padding":"30rpx 0 10rpx","fontSize":"40rpx","color":"#333","textAlign":"center","fontWeight":"bold"}'>互助需求</view> -->
				<view class="page-title" :style='{"padding":"30rpx 0 10rpx","fontSize":"40rpx","color":"#333","textAlign":"center","fontWeight":"bold"}'>预约帮助</view>
				<view class="cu-bar bg-white search" :style='{"padding":"30rpx 0 20rpx 0","margin":"0","background":"none","display":"flex","width":"100%","position":"relative","height":"auto"}'>
					<view :style='{"border":"none","margin":"0","borderRadius":"20rpx","flex":"1","background":"#fff","lineHeight":"100rpx","position":"relative","height":"100rpx"}' class="search-form round">
						<text class="icon iconfont icon-fangdajing07" :style='{"color":"rgb(153, 153, 153)","left":"0px","textAlign":"center","width":"100rpx","fontSize":"50rpx","lineHeight":"100rpx","position":"absolute","right":"0px"}'></text>
						<input placeholder-style="color: #666; font-size: 34rpx;" :style='{"border":"0","padding":"20rpx 20rpx 20rpx 100rpx","color":"#333","borderRadius":"50rpx","background":"none","width":"100%","lineHeight":"60rpx","fontSize":"34rpx","height":"100rpx"}' v-model="searchForm.xuqiubiaoti" type="text" placeholder="请输入互助标题关键词" ></input>
					</view>
					<button :style='{"border":"0","padding":"0px","margin":"0","color":"#fff","right":"4rpx","borderRadius":"50rpx","top":"30rpx","background":"linear-gradient( 135deg, #9EEEEB 0%, #99ABFF 100%)","width":"160rpx","lineHeight":"100rpx","fontSize":"34rpx","position":"absolute","height":"100rpx","fontWeight":"bold"}' @tap="search" class="cu-btn shadow-blur round">搜索</button>
				</view>
			
				<view class="sort-section" :style='{"padding":"20rpx 0","margin":"20rpx 0 30rpx","borderRadius":"12rpx","background":"#fff","width":"100%"}'>
					<view class="section-title" :style='{"fontSize":"36rpx","color":"#333","margin":"0 0 20rpx 30rpx","fontWeight":"bold"}'>排序方式</view>
					<view :style='{"flexWrap":"wrap","margin":"10rpx 0 10rpx 30rpx","display":"flex"}'>
						<view @click="sortClick('addtime')" :style='{"border":"2rpx solid #999","padding":"0 20rpx","margin":"0 30rpx 0 0","outline":"0","borderRadius":"12rpx","background":"#fff","display":"flex","height":"70rpx","alignItems":"center"}'>
							<text :style='{"color":"#333","lineHeight":"70rpx","fontSize":"32rpx"}'>按日期</text>
							<text v-if="listSort!='addtime'" class="icon iconfont icon-shijian18" :style='{"margin":"0 0 0 10rpx","lineHeight":"70rpx","fontSize":"32rpx","color":"#999"}'></text>
							<text v-else-if="listSort=='addtime'&&listOrder=='asc'" class="icon iconfont icon-shijian18" :style='{"margin":"0 0 0 10rpx","lineHeight":"70rpx","fontSize":"32rpx","color":"#5ba6df"}'></text>
							<text v-else-if="listSort=='addtime'&&listOrder=='desc'" class="icon iconfont icon-shijian18" :style='{"margin":"0 0 0 10rpx","lineHeight":"70rpx","fontSize":"32rpx","color":"#5ba6df"}'></text>
						</view>
					</view>
				</view>

				<view :style='{"width":"100%","background":"none","flexDirection":"column","display":"flex","height":"auto"}'>
					<!-- 样式1 -->
					<view class="uni-product-list" :style='{"padding":"0","margin":"20rpx 0 0","flexWrap":"wrap","flex":"auto","display":"flex","width":"100%","justifyContent":"space-between","height":"auto"}'>
						<view class="uni-product" :style='{"boxShadow":"0 5rpx 20rpx rgba(0,0,0,.2)","margin":"0 0 40rpx","backgroundColor":"#fff","borderRadius":"20rpx","flexWrap":"wrap","display":"flex","width":"100%","height":"auto"}' v-for="(product,index) in list" :key="index">
							<image :style='{"padding":"0","margin":"0","objectFit":"cover","borderRadius":"20rpx 20rpx 0 0","display":"block","width":"100%","height":"400rpx","order":"-1"}' mode="aspectFill" class="uni-product-image" v-if="preHttp(product.xuqiuzhaopian)" :src="product.xuqiuzhaopian.split(',')[0]"></image>
							<image :style='{"padding":"0","margin":"0","objectFit":"cover","borderRadius":"20rpx 20rpx 0 0","display":"block","width":"100%","height":"400rpx","order":"-1"}' mode="aspectFill" class="uni-product-image" v-else :src="product.xuqiuzhaopian?baseUrl+product.xuqiuzhaopian.split(',')[0]:''"></image>

							<view :style='{"padding":"30rpx","width":"100%"}'>
								<view class="uni-product-title" :style='{"padding":"0 0 20rpx 0","color":"#333","borderBottom":"1rpx solid #eee","textAlign":"center","width":"100%","lineHeight":"50rpx","fontSize":"36rpx","fontWeight":"bold"}'>{{product.xuqiubiaoti}}</view>
								
								<view :style='{"padding":"30rpx","width":"100%"}'>
									<view class="uni-product-title" :style='{"padding":"0 0 20rpx 0","color":"#333","borderBottom":"1rpx solid #eee","textAlign":"center","width":"100%","lineHeight":"50rpx","fontSize":"36rpx","fontWeight":"bold"}'>{{product.fuwubiaoti}}</view>
									
									<view :style='{"padding":"10rpx 0","display":"flex","flexDirection":"row","justifyContent":"space-around"}'>
										<view :style='{"textAlign":"center"}'>
											<text :style='{"color":"#666","lineHeight":"50rpx","fontSize":"32rpx"}'>状态：{{product.fuwuzhuangtai}}</text>
										</view>
										<view :style='{"textAlign":"center"}'>
											<text :style='{"color":"#666","lineHeight":"50rpx","fontSize":"32rpx"}'>积分：{{product.jifen}}</text>
										</view>
									</view>
									
									<view :style='{"padding":"10rpx 0","display":"flex","flexDirection":"row","justifyContent":"space-around"}'>
										<view :style='{"textAlign":"center"}'>
											<text class="icon iconfont icon-shijian21" :style='{"margin":"0 10rpx 0 0","lineHeight":"1.5","fontSize":"32rpx","color":"#666"}'></text>
											<text :style='{"color":"#666","lineHeight":"1.5","fontSize":"32rpx"}'>{{product.addtime.split(' ')[0].replace(/\-/g,'-')}}</text>
										</view>
										<view :style='{"textAlign":"center"}'>
											<text class="icon iconfont icon-geren16" :style='{"margin":"0 10rpx 0 0","lineHeight":"1.5","fontSize":"32rpx","color":"#666"}'></text>
											<text :style='{"color":"#666","lineHeight":"1.5","fontSize":"32rpx"}'>{{product.zhanghao}}</text>
										</view>
									</view>
								</view>
							</view>
							
							<!-- #ifdef MP-WEIXIN -->
							<view :style='{"width":"100%","padding":"20rpx 30rpx","justifyContent":"center","display":"flex","height":"auto"}'>
								<view :style='{"padding":"0 30rpx","margin":"0 20rpx 0 0","borderRadius":"12rpx","background":"#5ba6df","display":"flex","height":"80rpx","alignItems":"center"}' v-if="(userid && isAuth('huzhuxuqiu','修改')) || (!userid && isAuthFront('huzhuxuqiu','修改'))" @tap.stop.proevent="onUpdate" :data-row="product">
									<text :style='{"margin":"0 10rpx 0 0","fontSize":"32rpx","lineHeight":"80rpx","color":"#fff","display":"inline-block"}' class="cuIcon-edit"></text>
									<text :style='{"fontSize":"32rpx","lineHeight":"80rpx","color":"#fff","display":"inline-block"}'>修改</text>
								</view>
								<view :style='{"padding":"0 30rpx","borderRadius":"12rpx","background":"#df5b5b","display":"flex","height":"80rpx","alignItems":"center"}' v-if="(userid && isAuth('huzhuxuqiu','删除')) || (!userid && isAuthFront('huzhuxuqiu','删除'))" @tap.stop.proevent="onDelete" :data-row="product">
									<text :style='{"margin":"0 10rpx 0 0","fontSize":"32rpx","lineHeight":"80rpx","color":"#fff","display":"inline-block"}' class="cuIcon-delete"></text>
									<text :style='{"fontSize":"32rpx","lineHeight":"80rpx","color":"#fff","display":"inline-block"}'>删除</text>
								</view>
							</view>
							<!-- #endif -->
							<!-- #ifndef MP-WEIXIN -->
							<view :style='{"width":"100%","padding":"20rpx 30rpx","justifyContent":"center","display":"flex","height":"auto"}'>
								<view :style='{"padding":"0 30rpx","margin":"0 20rpx 0 0","borderRadius":"12rpx","background":"#5ba6df","display":"flex","height":"80rpx","alignItems":"center"}' v-if="(userid && isAuth('huzhuxuqiu','修改')) || (!userid && isAuthFront('huzhuxuqiu','修改'))" @tap.stop.proevent="onUpdateTap(product)">
									<text :style='{"margin":"0 10rpx 0 0","fontSize":"32rpx","lineHeight":"80rpx","color":"#fff","display":"inline-block"}' class="cuIcon-edit"></text>
									<text :style='{"fontSize":"32rpx","lineHeight":"80rpx","color":"#fff","display":"inline-block"}'>修改</text>
								</view>
								<view :style='{"padding":"0 30rpx","borderRadius":"12rpx","background":"#df5b5b","display":"flex","height":"80rpx","alignItems":"center"}' v-if="(userid && isAuth('huzhuxuqiu','删除')) || (!userid && isAuthFront('huzhuxuqiu','删除'))" @tap.stop.proevent="onDeleteTap(product.id)">
									<text :style='{"margin":"0 10rpx 0 0","fontSize":"32rpx","lineHeight":"80rpx","color":"#fff","display":"inline-block"}' class="cuIcon-delete"></text>
									<text :style='{"fontSize":"32rpx","lineHeight":"80rpx","color":"#fff","display":"inline-block"}'>删除</text>
								</view>
							</view>
							<!-- #endif -->
						</view>
					</view>
				</view>
				<button :style='{"border":"0","boxShadow":"0 5rpx 20rpx rgba(0,0,0,.3)","color":"rgb(255, 255, 255)","bottom":"30rpx","right":"30rpx","outline":"none","borderRadius":"50rpx","background":"linear-gradient( 135deg, #9EEEEB 0%, #99ABFF 100%)","width":"160rpx","lineHeight":"80rpx","fontSize":"34rpx","position":"fixed","height":"80rpx","zIndex":"9","fontWeight":"bold"}' v-if="userid && isAuth('huzhuxuqiu','新增')" class="add-btn" @click="onAddTap()">新增</button>
				<button :style='{"border":"0","boxShadow":"0 5rpx 20rpx rgba(0,0,0,.3)","color":"rgb(255, 255, 255)","bottom":"30rpx","right":"30rpx","outline":"none","borderRadius":"50rpx","background":"linear-gradient( 135deg, #9EEEEB 0%, #99ABFF 100%)","width":"160rpx","lineHeight":"80rpx","fontSize":"34rpx","position":"fixed","height":"80rpx","zIndex":"9","fontWeight":"bold"}'class="add-btn" @click="onAddTap()">新增</button>

				<button :style='{"border":"0","boxShadow":"0 5rpx 20rpx rgba(0,0,0,.3)","color":"rgb(255, 255, 255)","bottom":"30rpx","right":"30rpx","outline":"none","borderRadius":"50rpx","background":"linear-gradient( 135deg, #9EEEEB 0%, #99ABFF 100%)","width":"160rpx","lineHeight":"80rpx","fontSize":"34rpx","position":"fixed","height":"80rpx","zIndex":"9","fontWeight":"bold"}' v-if="!userid && isAuthFront('huzhuxuqiu','新增')" class="add-btn" @click="onAddTap()">新增</button>
			
			        <!-- <view v-if="showAgreementModal" class="modal-overlay" @click.stop>
			          <view class="modal-content">
			            <view class="modal-title">社区老人互助服务使用告知书</view>
			            <view class="modal-body">
			              <text>尊敬的老年朋友：</text><br/>
			              <text>感谢您使用本系统！为保障您的权益与安全，请您在使用前仔细阅读以下内容：</text<br/><br/>
			              
			              <text>1. 服务说明</text><br/>
			              <text>本系统旨在促进邻里互助，您可通过点击按钮发布或接受帮助需求（如代购物品、陪同就医等）。所有服务均为自愿参与，不涉及金钱交易。</text<br/><br/>
			              
			              <text>2. 风险提示</text><br/>
			              <text>• 助人前请评估自身健康状况，避免搬运重物、高空作业等高风险行为。</text><br/>
			              <text>• 服务过程中如感身体不适，请立即停止并联系子女/社区。</text><br/>
			              <text>• 建议两人以上同行开展户外帮扶。</text<br/><br/>
			              
			              <text>3. 紧急情况</text><br/>
			              <text>遇突发状况时请优先拨打120/110，并同步联系社区值班室（电话：13785386990）</text<br/><br/>
			              
			              <text>让我们携手共建安全温暖的互助社区！祝您使用愉快！</text<br/><br/>
			              
			              <text>乐龄社区服务中心</text><br/>
			              <text>2025年5月1日</text>
			            </view> -->
			           <!-- <button class="confirm-btn" @click="confirmAgreement">确认</button>
			          </view> -->
			        </view>
			</view>
		</view>
	</mescroll-uni>
</template>

<script>
	export default {
		data() {
			return {
				 showAgreementModal: true,
				btnColor: ['#409eff','#67c23a','#909399','#e6a23c','#f56c6c','#356c6c','#351c6c','#f093a9','#a7c23a','#104eff','#10441f','#a21233','#503319'],
				list: [],
				lists: [],
                userid: '',
				mescroll: null, //mescroll实例对象
				downOption: {
					auto: false //是否在初始化后,自动执行下拉回调callback; 默认true
				},
				upOption: {
					noMoreSize: 5, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
					textNoMore: '~ 没有更多了 ~',
				},
				hasNext: true,
				searchForm:{
					xuqiubiaoti: '',
				},
				CustomBar: '0',
				listSort: 'id',
				listOrder: 'desc',
				screenBoxShow: false,
			};
		},
		watch: {
		},
		mounted() {
		},
		computed: {
			baseUrl() {
				return this.$base.url;
			},
		},
		async onShow() {
			this.btnColor = this.btnColor.sort(()=> {
				return (0.5-Math.random());
			});
			this.hasNext = true
			// 重新加载数据
			if (this.mescroll) this.mescroll.resetUpScroll()
		},
		async onLoad(options) {
            if(options.userid) {
                this.userid=options.userid;
            } else {
                this.userid = "";
            }
			this.hasNext = true
			// 重新加载数据
			// if (this.mescroll) this.mescroll.resetUpScroll()
		},
		components: {
		},
		methods: {
			confirmAgreement(){
				this.showAgreementModal = false
			},
			screenReset(){
				this.searchForm = {}
				this.search()
				this.$forceUpdate()
			},
			uGetRect(selector, all) {
				return new Promise(resolve => {
					uni.createSelectorQuery()
					.in(this)
					[all ? 'selectAll' : 'select'](selector)
					.boundingClientRect(rect => {
						if (all && Array.isArray(rect) && rect.length) {
							resolve(rect);
						}
						if (!all && rect) {
							resolve(rect);
						}
					})
					.exec();
				});
			},
			cloneData(data) {
				return JSON.parse(JSON.stringify(data));
			},
			sortClick(type){
				if(this.listSort==type){
					if(this.listOrder == 'desc'){
						this.listOrder = 'asc'
					}else{
						this.listOrder = 'desc'
					}
				}else{
					this.listSort = type
					this.listOrder = 'desc'
				}
				this.search()
			},
            priceChange(price) {
                return Number(price).toFixed(2);
            },
            preHttp(str) {
                return str && str.substr(0,4)=='http';
            },
			//类别搜索
			// mescroll组件初始化的回调,可获取到mescroll对象
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			/*下拉刷新的回调 */
			downCallback(mescroll) {
				this.hasNext = true
				// 重置分页参数页数为1
				mescroll.resetUpScroll()
			},
			/*上拉加载的回调: mescroll携带page的参数, 其中num:当前页 从1开始, size:每页数据条数,默认10 */
			async upCallback(mescroll) {
				let params = {
					page: mescroll.num,
					limit: mescroll.size,
				}
				params['sort'] = this.listSort;
				params['order'] = this.listOrder;

           const zhanghao = uni.getStorageSync("appUserzhanghao") || '';
				 if (zhanghao) {
				     params['zhanghao'] = zhanghao; // 参数名必须为 zhanghao_ne
				 }
				 // 添加状态过滤条件
				     params['fuwuzhuangtai'] = '待处理'; // 只显示待处理状态
				if(this.searchForm.xuqiubiaoti){
					params['xuqiubiaoti'] = '%' + this.searchForm.xuqiubiaoti + '%'
				}
				let user = uni.getStorageSync("appUserid")?JSON.parse(uni.getStorageSync('userSession')):{}
                let res = {}
                if(this.userid) {
                    res = await this.$api.page(`huzhuxuqiu`, params);
                } else {
                    res = await this.$api.list(`huzhuxuqiu`, params);
                }

				// 如果是第一页数据置空
				if (mescroll.num == 1) this.list = [];
				this.list = this.list.concat(res.data.list);
				this.$forceUpdate()
				
				let length = Math.ceil(this.list.length/6)
				let arr = [];
				for (let i = 0; i<length; i++){
					arr[i] = this.list.slice(i*6, (i+1)*6)
				}
				this.lists = arr
				if (res.data.list.length == 0) this.hasNext = false;
				mescroll.endSuccess(mescroll.size, this.hasNext);
			},
			// 详情
			onDetailTap(item) {
                uni.setStorageSync("useridTag",this.userid);
				this.$utils.jump(`./detail?id=${item.id}&userid=`+this.userid)
			},
			onUpdate(e){
				this.onUpdateTap(e.currentTarget.dataset.row)
			},
			// 修改
			onUpdateTap(row){
                uni.setStorageSync("useridTag",this.userid);
				this.$utils.jump(`./add-or-update?id=${row.id}`)
			},
			// 添加
			onAddTap(){
                uni.setStorageSync("useridTag",this.userid);
				this.$utils.jump(`./add-or-update`)
			},
			onDelete(e){
				this.onDeleteTap(e.currentTarget.dataset.row.id)
			},
			onDeleteTap(id){
				var _this = this;
				uni.showModal({
					title: '提示',
					content: '是否确认删除',
					success: async function(res) {
						if (res.confirm) {
							await _this.$api.del('huzhuxuqiu', JSON.stringify([id]));
							_this.$utils.msg('删除成功');
							_this.hasNext = true
							// 重置分页参数页数为1
							_this.search()
						}
					}
				});
			},
			// 搜索
			async search(){
				this.mescroll.num = 1
				let searchForm = {
					page: this.mescroll.num,
					limit: this.mescroll.size,
				}
				searchForm['sort'] = this.listSort;
				searchForm['order'] = this.listOrder;
               const zhanghao = uni.getStorageSync("appUserzhanghao") || '';
				 if (zhanghao) {
				     searchForm['zhanghao'] = zhanghao; // 参数名必须为 zhanghao_ne
				 }
				 // 添加状态过滤条件
				     params['fuwuzhuangtai'] = '待处理'; // 只显示待处理状态
				if(this.searchForm.xuqiubiaoti){
					searchForm['xuqiubiaoti'] = '%' + this.searchForm.xuqiubiaoti + '%'
				}
                let res = {};
                if(this.userid) {
                    res = await this.$api.page(`huzhuxuqiu`, searchForm);
                } else {
                    res = await this.$api.list(`huzhuxuqiu`, searchForm);
                }
				// 如果是第一页数据置空
				if (this.mescroll.num == 1) this.list = [];
				this.list = this.list.concat(res.data.list);
				
				let length = Math.ceil(this.list.length/6)
				let arr = [];
				for (let i = 0; i<length; i++){
					arr[i] = this.list.slice(i*6, (i+1)*6)
				}
				this.lists = arr
				if (res.data.list.length == 0) this.hasNext = false;
				this.mescroll.endSuccess(this.mescroll.size, this.hasNext);
				this.screenBoxShow = false
			}
		}
	};
</script>

<style lang="scss" scoped>
	.content {
		min-height: calc(100vh - 44px);
		box-sizing: border-box;
		font-size: 34rpx;
	}
	
	.sort-section {
		box-shadow: 0 5rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.uni-product {
		transition: transform 0.2s;
	}
	
	.uni-product:active {
		transform: scale(0.98);
	}
	
	 .content {
	    min-height: calc(100vh - 44px);
	    box-sizing: border-box;
	    font-size: 34rpx;
	  }
	  
	  .sort-section {
	    box-shadow: 0 5rpx 10rpx rgba(0,0,0,0.1);
	  }
	  
	  .uni-product {
	    transition: transform 0.2s;
	  }
	  
	  .uni-product:active {
	    transform: scale(0.98);
	  }
	  
	 
	  .modal-overlay {
	    position: fixed;
	    top: 0;
	    left: 0;
	    width: 100%;
	    height: 100%;
	    background-color: rgba(0, 0, 0, 0.5); 
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    z-index: 999; 
	  }
	  
	.modal-content {
	    background-color: #fff;
	    width: 100%;
	    border-radius: 20rpx;
	    padding: 40rpx;
	    box-sizing: border-box;
	    position: relative;
	    max-height: 80vh; 
	    overflow-y: auto;
	}
	  
	  .modal-title {
	    font-size: 40rpx;
	    font-weight: bold;
	    margin-bottom: 40rpx;
	  }
	  
	  .modal-body {
	    text-align: left;
	    line-height: 1.6;
	    font-size: 32rpx;
	    margin-bottom: 40rpx;
	  }
	  
	  .confirm-btn {
	    width: 100%;
	    padding: 20rpx;
	    background-color: #5ba6df;
	    color: #fff;
	    border: none;
	    border-radius: 10rpx;
	    font-size: 32rpx;
	  }
	  
	  .confirm-btn:active {
	    opacity: 0.8;
	  }
</style>
